﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Client
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Thread threadClient;
            //创建一个线程 用于监听服务端发来的消息
            threadClient = new Thread(handshake);

            //将窗体线程设置为与后台同步
            threadClient.IsBackground = true;

            //启动线程
            threadClient.Start();
            Application.Run(new Form1());
        }
        static void handshake()
        {
            TcpConnection.getInstance().handshake((response) =>
            {
                if (response.code == 0)
                {
                    //链接成功
                    TcpConnection.getInstance().isConnected = true;
                    LogHelper.info("Connect successed.");
                }
            });
            while (true)
            {
                while (!TcpConnection.getInstance().connected())
                {
                    Thread.Sleep(4 * 60 * 1000);
                    if (!TcpConnection.getInstance().connected())
                    {
                        TcpConnection.getInstance().handshake((response) =>
                        {
                            if (response.code == 0)
                            {
                                //链接成功
                                TcpConnection.getInstance().isConnected = true;
                                LogHelper.info("Connect successed.");
                            }
                        });
                    }
                }

                while (TcpConnection.getInstance().connected())
                {
                    TcpConnection.getInstance().clientSendMsg(Global.getHeartJson(), (response) =>
                    {
                        //链接成功
                        LogHelper.info("Heart send successed.");
                    });
                    Thread.Sleep(4 * 60 * 1000);
                }
            }
        }
    }
}
